<template>
  <div class="common_settings">
    <div class="settings_group">
      <div class="settings_group_title">
        <a href="javascript:void(0)">系统快捷键</a>
      </div>
      <div class="settings_group_item"
           v-for="(item, index) in shortcuts.system"
           :key="index">
        <div class="settings_group_item_left"
             v-text="item.desc"></div>
        <Poptip trigger="click"
                word-wrap
                placement="left"
                :width="300"
                content="先按功能键（Command、Option、Control、Shift），再按其他普通键 或 按F1-F12单键">
          <div class="settings_group_item_right">
            <div class="shortcut_input"
                 tabindex="1"
                 @focus="setShortcutName(item)"
                 @blur="resetShortcutName"
                 @keydown="keydown"
                 @keyup="keyup">
              <span v-if="shortcutInput.main && activeShortcutUid == item.uid"
                    class="pen"
                    v-text="shortcutInput.main + '+' + shortcutInput.sub"></span>
              <a href="javascript:void(0)"
                 class="pen"
                 v-else
                 v-text="item.keys"></a>
            </div>
          </div>
        </Poptip>
      </div>

    </div>

    <div class="settings_group">
      <div class="settings_group_title">
        <a href="javascript:void(0)">插件快捷键</a>
      </div>
      <div class="settings_group_item"
           v-for="(item, index) in shortcuts.user"
           :key="index">
        <div class="settings_group_item_left"
             v-text="item.desc"></div>
        <Poptip trigger="click"
                word-wrap
                :width="300"
                placement="left"
                content="先按功能键（Command、Option、Control、Shift），再按其他普通键 或 按F1-F12单键">
          <div class="settings_group_item_right">
            <div class="shortcut_input"
                 tabindex="1"
                 @focus="setShortcutName(item)"
                 @blur="resetShortcutName"
                 @keydown="keydown"
                 @keyup="keyup">
              <span v-if="shortcutInput.main && activeShortcutUid == item.uid"
                    class="pen"
                    v-text="shortcutInput.main + '+' + shortcutInput.sub"></span>
              <a href="javascript:void(0)"
                 class="pen"
                 v-else
                 v-text="item.keys"></a>
            </div>
          </div>
        </Poptip>
      </div>

    </div>

    <!-- <div class="settings_group">
      <div class="settings_group_title">
        <a href="javascript:void(0)">插件设置</a>
      </div>
      <div class="settings_group_item"
           v-if="pluginsSettings.hasOwnProperty('autoUpgrade')">
        <div class="settings_group_item_left">
          自动安装新版本
          <Tooltip content="已安装的插件，自动更新到最新版本"
                   placement="top">
            <Icon type="ios-help-circle"
                  size="18"
                  color="#17a2b8" />
          </Tooltip>
        </div>
        <div class="settings_group_item_right">
          <div class="item_value">
            <iSwitch v-model="pluginsSettings.autoUpgrade"
                     @on-change="toggleAutoUpgrade"></iSwitch>
          </div>
        </div>
      </div>
    </div> -->
  </div>
</template>

<script>
import { Poptip, Tooltip, Switch, Icon } from 'view-design'
export default {
  name: 'CommonSettings',
  components: {
    Poptip, Tooltip,
    iSwitch: Switch,
    Icon
  },
  props: {
    activeTab: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      shortcuts: {
        system: [],
        user: []
      },
      activeShortcutName: '',
      activeShortcutUid: '',
      shortcutInput: {
        main: '',
        sub: ''
      },
      shortcutsMap: {
        'CommandOrControl': /macintosh|mac os x/i.test(navigator.userAgent) ? 'Command' : 'Control',
        'Meta': 'Command',
        'Slash': '/',
        'Backquote': '`',
        'Minus': '-',
        'Equal': '=',
        'Backslash': '\\',
        'BracketRight': ']',
        'BracketLeft': '[',
        'Semicolon': ';',
        'Quote': "'",
        'Comma': ',',
        'Period': '.',
        'ArrowRight': 'Right',
        'ArrowLeft': 'Left',
        'ArrowUp': 'Up',
        'ArrowDown': 'Down'
      },
      functionalKeys: ['Shift', 'Control', 'Alt', 'Meta'],
      pluginsSettings: {}
    }
  },
  watch: {
    activeTab: {
      immediate: true,
      handler (val) {
        if (val == 'Settings') {
          this.listShortcuts()
          // this.listPluginsSettings()
        }
      }
    }
  },
  mounted () {
    bbtools.on('shortcut-list-response', this.shortcutListResponse)
    bbtools.on('shortcut-update-response', this.shortcutUpdateResponse)
    bbtools.on('shortcut-remove-by-pid-response', this.shortcutRemoveByPidResponse)
  },
  methods: {
    translateShortcut (shortcut) {
      if (!shortcut) return ''
      let _shortcuts = shortcut.split('+')
      _shortcuts = _shortcuts.map(item => this.shortcutsMap[item] || item)
      return _shortcuts.join('+')
    },
    setShortcutName (item) {
      this.activeShortcutName = item.name
      this.activeShortcutUid = item.uid
    },
    resetShortcutName () {
      this.activeShortcutName = ''
      this.activeShortcutUid = ''
      this.shortcutInput.main = ''
      this.shortcutInput.sub = ''
    },
    updateShortcut (newShortcut) {
      if (!this.activeShortcutName) return
      bbtools.send('shortcut-update', {
        uid: this.activeShortcutUid,
        name: this.activeShortcutName,
        keys: newShortcut
      })
      // bbtools.send('update-shortcut', {
      //   name: this.activeShortcutName,
      //   newShortcut: newShortcut
      // })
      // this.shortcuts[this.activeShortcutName] = newShortcut
    },
    shortcutUpdateResponse (event, response) {
      if (response.code === 200) {
        this.$Message.success({
          content: '更新成功',
          background: true
        })
        let _index = -1
        for (let i = 0; i < this.shortcuts[response.data.type].length; i++) {
          if (this.shortcuts[response.data.type][i].uid === response.data.uid) {
            _index = i
            break
          }
        }
        if (_index > -1) {
          this.shortcuts[response.data.type].splice(_index, 1, JSON.parse(JSON.stringify(response.data)))
        }
      } else {
        this.$Message.error({
          content: response.message || '更新失败',
          background: true
        })
      }
    },
    shortcutRemoveByPidResponse (event, response) {
      if (response.code === 200) {
        let uids = response.data.map(item => item.uid)
        this.shortcuts.user = JSON.parse(JSON.stringify(this.shortcuts.user.filter(item => uids.indexOf(item.uid) > -1)))
      }
    },
    listShortcuts () {
      bbtools.send('shortcut-list', {
        type: 'system'
      })
      bbtools.send('shortcut-list', {
        type: 'user'
      })
    },
    shortcutListResponse (event, response) {
      if (response.code === 200) {
        if (response.type) {
          this.shortcuts[response.type] = response.data || []
        }
      }
    },
    listPluginsSettings () {
      this.pluginsSettings = bbtools.sendSync('list-plugins-settings')
    },
    toggleAutoUpgrade (status) {
      let response = bbtools.sendSync('set-auto-upgrade-settings', {
        autoUpgrade: status
      })
      if (response.autoUpgrade != status) {
        this.pluginsSettings.autoUpgrade = response.autoUpgrade
      }
    },
    keydown (e) {
      e.preventDefault()
      e.stopPropagation()
      const singalKeys = ['F1', 'F2', 'F3', 'F4', 'F5', 'F6', 'F7', 'F8', 'F9', 'F10', 'F11', 'F12']
      if (!this.shortcutInput.main && (singalKeys.indexOf(e.key) > -1)) {
        this.updateShortcut(e.key)
      } else if (this.functionalKeys.indexOf(e.key) > -1) {
        this.shortcutInput.main = this.translateShortcut(e.key)
      } else {
        if (!this.shortcutInput.main) {

        } else {
          this.shortcutInput.sub = this.translateShortcut(e.code.replace(/^(Key)|(Digit)/, ''))
        }
      }
    },
    keyup (e) {
      e.preventDefault()
      e.stopPropagation()
      if (this.shortcutInput.main && this.shortcutInput.sub) {
        this.updateShortcut(this.shortcutInput.main + '+' + this.shortcutInput.sub)
        this.shortcutInput.main = ''
        this.shortcutInput.sub = ''
      } else {
        if (this.functionalKeys.indexOf(e.key) > -1) {
          this.shortcutInput.main = ''
          this.shortcutInput.sub = ''
        } else {
          this.shortcutInput.sub = ''
        }
      }
    }
  }
}
</script>

<style lang="less" scoped>
@import url("../../themes/index.less");
.common_settings {
  width: 100%;
  height: 100%;
  // display: flex;
  // flex-direction: row;
  // align-items: center;
  // justify-content: center;
  .settings_group {
    width: 100%;
    padding: 10px 15px;
    box-sizing: border-box;
    &_title {
      height: 32px;
      display: flex;
      flex-direction: row;
      align-items: center;
    }
    &_item {
      width: 100%;
      height: 42px;
      display: flex;
      flex-direction: row;
      align-items: center;
      justify-content: space-between;
      &_left {
        width: 40%;
        min-width: 150px;
        height: 100%;
        padding-left: 15px;
        display: flex;
        flex-direction: row;
        align-items: center;
        justify-content: flex-start;
      }
      &_right {
        flex: 1;
        height: 100%;
        cursor: pointer;
        display: flex;
        flex-direction: row;
        align-items: center;
        justify-content: flex-end;
        .shortcut_input {
          width: 300px;
          height: 36px;
          border: 1px solid @darkDividerColor;
          border-radius: 4px;
          cursor: pointer;
          display: flex;
          flex-direction: row;
          align-items: center;
          justify-content: center;
        }
        .item_value {
          width: 300px;
          height: 100%;
          cursor: pointer;
          display: flex;
          flex-direction: row;
          align-items: center;
          justify-content: flex-start;
        }
      }
    }
  }
}
.pen {
  pointer-events: none;
}
</style>